package com.changgou.consume.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.consume.config.RabbitMQConfig;
import com.changgou.consume.service.SecKillOrderService;
import com.changgou.seckill.pojo.SeckillOrder;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ConsumeListener {

    @Autowired
    private SecKillOrderService secKillOrderService;

    @RabbitListener(queues = RabbitMQConfig.SECKILL_ORDER_QUEUE)
    public void receiveSecKillOrderMessage(Channel channel, Message message){

        //设置与抓取总数
        try {
            channel.basicQos(300);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //转换消息
        SeckillOrder secKillOrder = JSON.parseObject(message.getBody(), SeckillOrder.class);

        //同步数据库订单
        int rows = secKillOrderService.handleCreateOrder(secKillOrder);
        if (rows>0){
            //返回成功消息
            try {
                //第一个参数：消息的唯一标识  boolean：代表是否开启批处理
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                //第一个参数：消息的唯一标识
                //第二个参数：true所有消费者都会拒绝这个消息,false只有当前消费者拒绝
                //第三个参数：true当前消息返回队列 ，false当前消息被丢弃(进入死信队列)
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
